import {Component, OnInit} from '@angular/core';
import {NzMessageService} from 'ng-zorro-antd/message';
import {UploadFile} from 'ng-zorro-antd/upload';
import {Observable, Observer} from 'rxjs';
import {Service} from '../service/service';
import {Http} from '../service/http';
import {Config} from '../service/config';
import {HttpClient} from '@angular/common/http';

@Component({
  selector: 'app-carousel',
  templateUrl: './carousel.component.html',
  styleUrls: ['./carousel.component.scss']
})
export class CarouselComponent implements OnInit {
  API_URL:string = '';
  header:object = {
    token : ''
  };
  constructor(private msg: NzMessageService, private service: Service, private http: Http, private httpClient: HttpClient) {
    this.header['token'] = localStorage.getItem('token');
    this.API_URL = Config.API_URL;
    this.getBanner();
  }

  title = '';
  image = '';
  htmlcontext = '';
  loading = false;
  avatarUrl: string;
  editor: any = {};
  editId = 0;
  listOfData = [];
  visible = false;

  getBanner() {
    this.service.bannerQuery(null, (result) => {
      result.data.forEach(item => {
        item.image = Config.API_URL + item.image;
      });
      this.listOfData = result.data;
      console.log(result);

    });
  }

  update() {
    const data = {
      id: this.editId,
      title: this.title,
      image: this.image.replace(Config.API_URL, ''),
      content: this.htmlcontext
    }
    this.service.bannerUpdate(data, (result) => {
      console.log(result);
      if (result.status == 1) {
        this.msg.info('修改成功');
      }else{
        this.msg.error('修改失败');
      }
      this.getBanner();
      this.visible = false;
    });
  }

  editFun(data) {
    this.editId = data.id;
    this.title = data.title;
    this.avatarUrl = data.image;
    this.htmlcontext = data.content;
    this.visible = true;
  }

  ngOnInit(): void {

  }

  open(): void {
    this.visible = true;
    this.title = '';
    this.image = '';
    this.avatarUrl = '';
    this.htmlcontext = '';
    this.editId = 0;
  }

  close(): void {
    this.visible = false;
  }

  submit() {
    const data = {
      title: this.title,
      image: this.image,
      content: this.htmlcontext
    };
    this.service.bannerAdd(data, (result) => {
      if (result.status == 1) {
        this.msg.info('添加成功');
      }else{
        this.msg.error('添加失败');
      }
      this.getBanner();
      this.close();
    });
  }

  beforeUpload = (file: File) => {
    return new Observable((observer: Observer<boolean>) => {
      const isJPG = file.type === 'image/jpeg' || 'image/png';
      if (!isJPG) {
        this.msg.error('You can only upload JPG PNG file!');
        observer.complete();
        return;
      }
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.msg.error('Image must smaller than 5MB!');
        observer.complete();
        return;
      }
      // check height
      this.checkImageDimension(file).then(dimensionRes => {
        if (!dimensionRes) {
          this.msg.error('最低宽600，宽300');
          observer.complete();
          return;
        }
        observer.next(isJPG && isLt5M && dimensionRes);
        observer.complete();
      });
    });
  }

  private getBase64(img: File, callback: (img: string) => void): void {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result!.toString()));
    reader.readAsDataURL(img);
  }

  private checkImageDimension(file: File): Promise<boolean> {
    return new Promise(resolve => {
      const img = new Image(); // create image
      img.src = window.URL.createObjectURL(file);
      img.onload = () => {
        const width = img.naturalWidth;
        const height = img.naturalHeight;
        console.log(width, height);
        window.URL.revokeObjectURL(img.src!);
        // resolve(width === height && width >= 50);
        resolve(width > 600 && height >= 300);
      };
    });
  }

  handleChange(info: { file: UploadFile }): void {
    switch (info.file.status) {
      case 'uploading':
        this.loading = true;
        break;
      case 'done':
        // Get this url from response in real world.
        this.getBase64(info.file!.originFileObj!, (img: string) => {
          const result = JSON.parse(info.file.response);
          if (result.success == 1) {
            this.msg.info('图片上传成功');
            // this.image = Config.API_URL + result.path;
            console.log(result.path)
            this.image = result.path;
            this.loading = false;
            this.avatarUrl = img;
          }
        });
        break;
      case 'error':
        this.msg.error('Network error');
        this.loading = false;
        break;
    }
  }

  /*富文本*/
  EditorCreated(quill) {
    const toolbar = quill.getModule('toolbar');
    toolbar.addHandler('image', this.imageHandler.bind(this));
    this.editor = quill;
  }

  imageHandler() {
    const Imageinput = document.createElement('input');
    Imageinput.setAttribute('type', 'file');
    Imageinput.setAttribute('accept', 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon');
    Imageinput.classList.add('ql-image');
    Imageinput.addEventListener('change', () => {
      const file = Imageinput.files[0];
      const data: FormData = new FormData();
      data.append('file', file, file.name);
      if (Imageinput.files != null && Imageinput.files[0] != null) {
        this.service.uploadImg(data, (result) => {
          console.log(result);
          const url = Config.API_URL + result.path;
          this.htmlcontext = this.htmlcontext + `<img src="${url}" width="100%"/>`
          const range = this.editor.getSelection(true);
          const index = range.index + range.length;
          this.editor.insertEmbed(range.index, 'image', url);
        });
      }
    });
    Imageinput.click();
  }
}
interface ValueObject {
  path?: string
}
